import { PageContainer } from '@ant-design/pro-layout';
import ProCard from '@ant-design/pro-card';
import ProTable from '@ant-design/pro-table';
import { useEffect, useState, useRef } from 'react';
import { Button, Divider, Tag, message, Menu, } from 'antd';
import Confirm from '@/components/common/Confirm';
import { tree, remove } from '@/services/system/resource/menu';
import { listAll } from '@/services/system/resource/module';
import styles from './index.less';
import SystemMenuForm from './components/form';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';

const SystemMenu = () => {
  const actionRef = useRef();

  const [formVisible, handleFormVisible] = useState(false);
  const [formValues, handleFormValues] = useState({});
  const [moduleList, handleModuleList] = useState([]);
  const [moduleKeys, handleModuleKeys] = useState([]);

  const indexStatusMap = {
    YES: { color: 'red', text: '是', },
    NO: { color: 'green', text: '否', }
  }

  useEffect( () => {
    const lostData = async () => {
      const result = await listAll();
      const data = result.data;

      if (data && data.length > 0) {
        handleModuleKeys([data[0].resourceId.toString()])
        if (actionRef.current) {
          actionRef.current.reset();
        }
      }

      return data;
    };

    lostData().then((data) =>{
      handleModuleList(data)
    });
  }, []);

  const selectModuleHandle = ({ item, key }) => {
    handleModuleKeys([key.toString()])
    if (actionRef.current) actionRef.current.reset();
  }

  const handleRaise = () => {
    handleFormValues({sort: 1});
    handleFormVisible(true);
  }

  const handleModify = (record) => {
    handleFormValues(record);
    handleFormVisible(true);
  }

  const handleDelete = (record) => {
    Confirm.delete({
      content: `<p>名称为 <span style="color: #f60"> ${record.name} </span> 的系统菜单将被删除</p><p>是否继续？</p>`,
      confirm: () => {
        remove(record.menuId).then((data) => {
          if (data.success) {
            if (actionRef.current) actionRef.current.reset();
            message.success('删除成功!');
          } else {
            message.error('删除失败!');
          }
        });
      },
    });
  };

  const columns = [
    { title: '菜单名称', dataIndex: 'name' },
    { title: '图标', dataIndex: 'icon', search: false },
    { title: '浏览路径', dataIndex: 'path', search: false },
    { title: '组件路径', dataIndex: 'component', search: false },
    { title: '菜单排序', dataIndex: 'sort', search: false },
    { title: '展示方式', dataIndex: 'showType', search: false, },
    { 
      title: '是否主页', dataIndex: 'isIndex', search: false, 
      render: (_, record) => <Tag color={indexStatusMap[record.isIndex].color}>{indexStatusMap[record.isIndex].text}</Tag>,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        return (
          <>
            <a onClick={() => { handleModify(record); }}> <EditOutlined/> 修改 </a>
            <Divider type="vertical" />
            <a onClick={() => { handleDelete(record) }}> <DeleteOutlined/> 删除 </a>
          </>
        );
      },
    },
  ];

  const menuItem = moduleList.map(module => <Menu.Item key={module.resourceId}> {module.name} </Menu.Item>);

  return (
    <PageContainer>
      
      <ProTable
        headerTitle={`菜单信息查询列表`}
        rowKey="id"
        search={false}
        manualRequest={true}
        actionRef={actionRef}
        toolBarRender={() => [
          <Button type="primary" onClick={() => { handleRaise(); }}> 新建 </Button>,
        ]}
        request={ async (params) => {
          if (moduleKeys.length <= 0)  return {};

          const response = await tree(moduleKeys[0]);
          return response;
        }}
        columns={columns}
        pagination={false}
        tableRender={(_, dom) => (
          <ProCard split="vertical">
            <ProCard colSpan={4} title="系统模块列表" className={styles.systemListContainer}>
              <Menu mode="inline" selectedKeys={moduleKeys}  onClick={selectModuleHandle}> {menuItem} </Menu>
            </ProCard>
            <ProCard colSpan={20} headerBordered className={styles.menuListContainer}>
              {moduleKeys.length > 0 ? dom : null}
            </ProCard>
          </ProCard>
        )}
      />

      {
        formVisible &&
        <SystemMenuForm 
          onSubmit={() => {
            if (actionRef.current) actionRef.current.reset();
            handleFormVisible(false);
          }}
          onCancel={() => {
            handleFormVisible(false);
          }}
          formVisible={formVisible}
          values={formValues}
        />
      }
    </PageContainer>
  );
};

export default SystemMenu;
